package cn.jcet.gumall.product.service.impl;

import cn.jcet.common.constant.ProductConstant;
import cn.jcet.gumall.product.dao.AttrAttrgroupRelationDao;
import cn.jcet.gumall.product.dao.AttrGroupDao;
import cn.jcet.gumall.product.dao.CategoryDao;
import cn.jcet.gumall.product.entity.*;
import cn.jcet.gumall.product.service.CategoryService;
import cn.jcet.gumall.product.vo.AttrRealationVo;
import cn.jcet.gumall.product.vo.AttrRespVo;
import cn.jcet.gumall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jcet.common.utils.PageUtils;
import cn.jcet.common.utils.Query;

import cn.jcet.gumall.product.dao.AttrDao;
import cn.jcet.gumall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    /**
     * 属性分组关系
     */
    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {

        AttrEntity attrEntity = new AttrEntity();

        // copy到对象中
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存基本数据
        this.save(attrEntity);
        // 保存关联关系 等于基本类型就保存
        if (attrEntity.getValueType() == ProductConstant.AttrEmuns.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            this.relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", ProductConstant.ATTR_BAES.equalsIgnoreCase(attrType) ? ProductConstant.AttrEmuns
                .ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEmuns.ATTR_TYPE_SALE.getCode());

        // 判断如果不等于0，肯定就有传递id
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        // 获取key，进行模糊查询，以id和name进行匹配
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or()
                        .like("attr_name", key);
            });
        }
        // 如果为0全查
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        // 使用流式操作数据
        List<AttrRespVo> list = page.getRecords().stream()
                .map(attrEntity -> {
                    // 创建封装的vo对象
                    AttrRespVo attrRespVo = new AttrRespVo();
                    BeanUtils.copyProperties(attrEntity, attrRespVo);
                    // 判断是否等于基本属性
                    if (ProductConstant.ATTR_BAES.equalsIgnoreCase(attrType)) {
                        // 根据分组条件查询
                        AttrAttrgroupRelationEntity relationEntity = this.relationDao
                                .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                                        .eq("attr_id", attrEntity.getAttrId()));
                        if (relationEntity != null && relationEntity.getAttrGroupId() !=null) {
                            AttrGroupEntity groupEntity = this.attrGroupDao.selectById(relationEntity.getAttrGroupId());
                            attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                        }
                    }
                    // 2、在属性id中获取分组id进行查询

                    // 判断数据不为空，设置name
                    CategoryEntity categoryEntity = this.categoryDao.selectById(attrEntity.getCatelogId());
                    if (categoryEntity != null) {
                        attrRespVo.setCatelogName(categoryEntity.getName());
                    }
                    return attrRespVo;
                }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        // 创建vo
        AttrRespVo attrRespVo = new AttrRespVo();
        // 创建原有实体类
        AttrEntity attrEntity = this.getById(attrId);
        // 属性copy
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        // 根据属性分组查询
        AttrAttrgroupRelationEntity relationEntity = this.relationDao
                .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrId));
        // 设置分组
        if (relationEntity != null) {
            attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = this.attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        // 设置分类
        Long catelogId = attrEntity.getCatelogId();
        // 递归查询子节点
        Long[] byCateLogPath = categoryService.findByCateLogPath(catelogId);
        attrRespVo.setCatelogPath(byCateLogPath);
        // 设置分类名称
        CategoryEntity categoryEntity = this.categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Override
    public void updateAttrById(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        // 属性拷贝
        BeanUtils.copyProperties(attr, attrEntity);
        // 修改
        this.updateById(attrEntity);
        // 如果是attr_value就进行修改保存
        if (attrEntity.getValueType() == ProductConstant.AttrEmuns.ATTR_TYPE_BASE.getCode()) {
            // 修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            // 设置 分组id
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            // 设置属性id
            relationEntity.setAttrId(attrEntity.getAttrId());
            // 判断，如果数量大于0执行修改，小于0表示插入
            int count = this.relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                // 更新
                this.relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                // 插入
                this.relationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> findAttrRelation(Long attrgroupId) {
        // 根据分组id查询，
        List<AttrAttrgroupRelationEntity> relationEntities = this.relationDao.
                selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = relationEntities.stream().map(attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());
        // 根据id查询l
        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void delectRelation(AttrRealationVo[] attrRealationVos) {

        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(attrRealationVos).stream()
                .map(item -> {
                    AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                    // 将分组id和属性id都复制到属性实体类中
                    BeanUtils.copyProperties(item, relationEntity);
                    return relationEntity;
                }).collect(Collectors.toList());

        // 批量删除方法
        this.relationDao.delectBatchAttr(entities);

    }

    @Override
    public PageUtils getNoRelation(Map<String, Object> params, Long attrgroupId) {
        // 1、当前分组只能关联自己所属分类的所有属性
        AttrGroupEntity attrGroupEntity = this.attrGroupDao.selectById(attrgroupId);
        // 获取分类id
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联级别别的分组没有被引用的属性
        List<AttrGroupEntity> group = this.attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.1、当前分类下的其他分组
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", collect));
        List<Long> attrIds = relationEntities.stream()
                .map(item -> {
                    return item.getAttrId();
                }).collect(Collectors.toList());

        // 拼装查询条件
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEmuns.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            // not in 如果存在null则查不出数据，相反就会存在数据
            attrEntityQueryWrapper.notIn("attr_id", attrIds);
        }
        // 模糊查询
        String key = (String) params.get("key");
//        this.getKey(key);
        if (!StringUtils.isEmpty(key)) {
            attrEntityQueryWrapper.and(obj -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        //2.2、分组关联的属性
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }
}